from typing import List, Dict
from src.utils.api_client import client
from src.utils.model_helper import MODEL

class AcademicAnalyzer:
    def __init__(self):
        self.model = MODEL
        self.client = client
    
    def analyze_content(self, text: str) -> Dict:
        """增强型学术分析"""
        try:
            prompt = f"""请执行以下分析步骤：
            1. 领域分类：[计算机视觉/NLP/机器学习]
            2. 创新点提取（按重要性排序）
            3. 矛盾点检测（与已有研究对比）
            4. 技术演进路径推断
            
            原文：{text[:2000]}"""
            
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "你是一个专业的学术论文分析助手。"},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.3
            )
            
            return {
                'content': response.choices[0].message.content,
                'status': 'success'
            }
            
        except Exception as e:
            return {
                'content': str(e),
                'status': 'error'
            }
    
    def _compare_methods(self, paper: Dict) -> Dict:
        """分析单篇论文的方法特点"""
        try:
            prompt = f"""请分析以下论文的方法特点：
            标题：{paper.get('title', '')}
            内容：{paper.get('content', '')[:1000]}
            
            请从以下几个方面进行分析：
            1. 核心方法
            2. 创新点
            3. 优势
            4. 局限性"""
            
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "你是一个专业的学术论文分析助手。"},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.3
            )
            
            return {
                'paper_id': paper.get('paper_id'),
                'analysis': response.choices[0].message.content
            }
            
        except Exception as e:
            return {
                'paper_id': paper.get('paper_id'),
                'analysis': str(e)
            }
    
    def _format_markdown_table(self, comparisons: List[Dict]) -> str:
        """将方法对比结果格式化为Markdown表格"""
        if not comparisons:
            return ""
        
        # 提取所有分析结果
        analyses = [comp['analysis'] for comp in comparisons if comp.get('analysis')]
        
        # 生成表格头
        table = "| 论文 | 核心方法 | 创新点 | 优势 | 局限性 |\n"
        table += "|------|----------|--------|------|--------|\n"
        
        # 为每个分析结果生成一行
        for i, analysis in enumerate(analyses):
            paper_id = comparisons[i].get('paper_id', f'Paper {i+1}')
            # 简单处理分析文本，提取关键信息
            sections = analysis.split('\n')
            method = next((s for s in sections if '核心方法' in s), '').replace('核心方法：', '').strip()
            innovation = next((s for s in sections if '创新点' in s), '').replace('创新点：', '').strip()
            advantages = next((s for s in sections if '优势' in s), '').replace('优势：', '').strip()
            limitations = next((s for s in sections if '局限性' in s), '').replace('局限性：', '').strip()
            
            table += f"| {paper_id} | {method} | {innovation} | {advantages} | {limitations} |\n"
        
        return table
    
    def generate_comparison_table(self, papers: List[Dict]) -> str:
        """自动生成方法对比表格"""
        # 对每篇论文进行分析
        comparisons = [self._compare_methods(p) for p in papers]
        
        # 格式化为Markdown表格
        return self._format_markdown_table(comparisons)